package com.ruoyi.web.web.api;

import com.ruoyi.accountant.service.AccountService;
import com.ruoyi.accountant.service.CurrencyService;
import com.ruoyi.accountant.service.ReasonService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.web.web.dto.MessageDto;
import com.ruoyi.web.web.form.IncomeForm;
import com.ruoyi.web.web.form.PayForm;
import com.ruoyi.web.web.form.TransferForm;
import com.ruoyi.web.web.form.Validation;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/***
 * 账户
 */
@RestController("accountControllerApi")
@RequestMapping("/api")
public class AccountController {
    @Resource
    private AccountService accountService;

    @Resource
    private CurrencyService currencyService;

    @Resource
    private ReasonService reasonService;

    /***
     * 账户收入
     * @return
     */
    @PostMapping("/income")
    public AjaxResult income(@RequestBody IncomeForm accountForm, HttpSession session) {
        System.out.println(accountForm.toString());
        Validation validate = accountForm.validate(false, accountService, currencyService, reasonService, session);
        if(validate.getOk()) {
            return AjaxResult.success(accountService.income(accountForm));
        } else {
            return AjaxResult.error();
        }

    }

    /***
     * 账户支出
     * @return
     */
    @PostMapping("/pay")
    public AjaxResult pay(@RequestBody PayForm payForm, HttpSession session) {
        Validation validate = payForm.validate(false, accountService,currencyService,reasonService, session);
        if(validate.getOk()) {
            return AjaxResult.success(accountService.pay(payForm));
        } else {
            return AjaxResult.error();
        }
    }

    @PostMapping("/transfer")
    public MessageDto transfer(@RequestBody TransferForm transferForm, Model model) {
        Validation validate = transferForm.validate(false, accountService, currencyService);
        if(validate.getOk()) {
            accountService.transfer(transferForm);
        } else {
            return new MessageDto(400, validate.getMessage());
        }
        model.addAttribute("transferForm", transferForm);
        return MessageDto.ok();
    }
}
